<template>
    <!-- 输入工资 -->
    <div class="insertSalary">
        <van-nav-bar title="输入工资" left-arrow @click-left="goBack()">
        </van-nav-bar>
        <!-- 默认模板 -->
        <van-cell class="defaultSalary" @click="toDetail" is-link>
            <template #title>
                <span class="custom-title">{{categoryid ? '已选模板' : '默认模板'}}</span>
                <span>{{defaultTemplate ? defaultTemplate.category.categoryname : ''}}</span>
            </template>
        </van-cell>
        <!-- 输入框 -->
        <div v-for="(item,index) in list" :key='index' class='row-input'>
            <van-cell-group v-if="!hasSalaryInfo || categoryid">
                <van-field autocomplete="off" clearable type="number" v-model="item.insert" :label="item.value"
                    :disabled="inputDisabled && !categoryid" :placeholder="'请输入'+item.value" />
            </van-cell-group>
        </div>
        <div v-for="(item,index) in salaryList" :key='index+"_"' class='row-input'>
            <van-cell-group v-if="hasSalaryInfo && !categoryid">
                <van-field autocomplete="off" clearable type="number" v-model="item.insert" :label="item.value" :disabled="inputDisabled"
                    :placeholder="'请输入'+item.value" />
            </van-cell-group>
        </div>
        <!-- 完成 -->
        <div class='bottom-btn'>
            <van-button class="btn-flex" @click="saveSalaryInfo()" type="info">保存</van-button>
            <van-button v-if="hasSalaryInfo && !categoryid && inputDisabled" plain type="primary" class="btn-flex"
                @click="edit">修改</van-button>
            <van-button v-else plain type="info" class="btn-flex" @click="cancel">退出
            </van-button>
        </div>
        <div style="height:50px"></div>
    </div>
</template>

<script>
import {Toast, Dialog} from 'vant'
import {th} from 'date-fns/locale'

export default {
  data() {
    return {
      list: [
        {
          value: '实发工资',
          insert: ''
        }
      ],
      salaryList: [], // 已有工资条

      CompanyID: '',
      JobUserId: '',
      JobId: '',
      salaryTemplateList: [],

      defaultTemplate: null, // 默认模板
      categoryid: '', // 选择的模板
      inputDisabled: true, // 输入框是否可输入：ture 不可输入； false 可输入；
      hasSalaryInfo: false, // 是否已有工资
      SalaryInfoId: '', // 已有工资ID
      SalaryCategoryid: '' // 已有工资模板ID
    }
  },
  mounted() {},
  async created() {
    this.CompanyID = this.$route.query.companyid
    this.JobUserId = this.$route.query.jobuserid
    this.JobId = this.$route.query.jobid
    this.categoryid = this.$route.query.categoryid

    // 获取所有的工资条模板
    this.getList()

    this.getLastNotCheckSalaryInfo()
  },
  methods: {
    // 创建工资条
    saveSalaryInfo() {
      if (!this.hasSalaryInfo) {
        // 创建工资条
        if (this.list[this.list.length - 1].insert.trim() == '' || this.list[this.list.length - 1].insert.trim() == 0) {
          Toast.fail("您还未填写 '实发工资'")
          return
        }

        let SalaryList = ''
        for (let i in this.list) {
          let item = {
            value: this.list[i].value,
            insert: ''
          }

          if (this.list[i].insert.trim() != '') {
            item.insert = this.list[i].insert
          } else {
            item.insert = 0
          }

          SalaryList = SalaryList + `${item.value}:${item.insert},`
        }

        let params = {
          SalaryList: SalaryList.slice(0, -1),
          CategoryId: this.defaultTemplate.category.categoryid,
          CompanyID: this.CompanyID,
          JobUserid: this.JobUserId,
          jobId: this.JobId
        }

        let that = this
        this.$api.myCompany.createSalaryInfo(params).then(res => {
          if (res.code === 200) {
            if (res.data == '该员工已经有数据') {
              Toast.fail('该员工已经有数据！')
              return
            }
            try {
              let result = JSON.parse(res.data)
              if (result.result == '0') {
                Toast.fail('操作失败请重试！')
                return
              }
            } catch {
              Toast.fail('操作失败请重试！')
              return
            }

            Toast.success('保存成功')
            setTimeout(() => {
              that.getLastNotCheckSalaryInfo()
            }, 500)
          } else {
            Toast('操作失败请重试！')
          }
        })
      } else {
        let params = {
          JobUserid: this.JobUserId,
          jobId: this.JobId,
          CompanyID: this.CompanyID,
          CategoryId: '',
          SalaryInfoId: this.SalaryInfoId,
          SalaryList: ''
        }

        // 修改工资条
        if (this.categoryid) {
          // 重新选择了工资模板
          if (
            this.list[this.list.length - 1].insert.trim() == '' ||
            this.list[this.list.length - 1].insert.trim() == 0
          ) {
            Toast.fail("您还未填写 '实发工资'")
            return
          }

          let SalaryList = ''
          for (let i in this.list) {
            let item = {
              value: this.list[i].value,
              insert: ''
            }

            if (this.list[i].insert.trim() != '') {
              item.insert = this.list[i].insert
            } else {
              item.insert = 0
            }

            SalaryList = SalaryList + `${item.value}:${item.insert},`
          }

          params.CategoryId = this.categoryid
          params.SalaryList = SalaryList.slice(0, -1)
        } else {
          // 原工资模板
          let SalaryList = ''
          let payroll = 0 // 实发工资
          for (let i in this.salaryList) {
            if (this.salaryList[i].value === '实发工资') {
              payroll = this.salaryList[i].insert
            }
            let item = {
              value: this.salaryList[i].value,
              insert: ''
            }

            if (this.salaryList[i].insert.trim() != '') {
              item.insert = this.salaryList[i].insert
            } else {
              item.insert = 0
            }

            SalaryList = SalaryList + `${item.value}:${item.insert},`
          }

          if (payroll.trim() == '' || payroll.trim() == 0) {
            Toast.fail("您还未填写 '实发工资'")
            return
          }

          params.CategoryId = this.SalaryCategoryid
          params.SalaryList = SalaryList.slice(0, -1)
        }

        let that = this
        this.$api.myCompany.updateSalaryInfo(params).then(res => {
          if (res.code === 200) {
            try {
              let result = JSON.parse(res.data)
              if (result.result == 1) {
                Toast.success('保存成功')
                setTimeout(() => {
                  that.getLastNotCheckSalaryInfo()
                }, 500)
              } else {
                Toast.fail('操作失败请重试！')
                return
              }
            } catch {
              Toast.fail('操作失败请重试！')
              return
            }
          } else {
            Toast('操作失败请重试！')
          }
        })
      }
    },
    cancel() {
      Dialog.confirm({
        title: '提示',
        message: '确定退出吗？'
      })
        .then(() => {
          this.goBack()
        })
        .catch(() => {})
    },

    // 未发工资可以修改
    edit() {
      this.inputDisabled = false
    },

    toDetail() {
      console.log(this.$route)
      this.$router.push({
        path: `/myCompany/salaryModel/companyID=${this.$route.query.companyid}`,
        query: {
          jobid: this.JobId,
          jobuserid: this.$route.query.jobuserid
        }
      })
    },

    // 获取所有的工资条模板
    async getList() {
      let param = {
        CompanyID: this.CompanyID,
        JobId: this.JobId,
        JobUserId: this.JobUserId
      }

      const result = await this.$api.myCompany.getSalaryCategory(param)
      if (result.code == 200 && result.data.data.length > 0) {
        this.salaryTemplateList = result.data.data
        // 设置默认模板
        for (let temp of result.data.data) {
          if (this.categoryid) {
            if (temp.category && temp.category.categoryid === this.categoryid) {
              this.defaultTemplate = temp
              break
            }
          } else if (temp.category && temp.category.categoryid === result.data.default.defaultCategoryid) {
            this.defaultTemplate = temp
            break
          }
        }
        if (!this.defaultTemplate) {
          this.defaultTemplate = result.data.data[0]
        }
        this.initSalaryCategoryList()
        console.log('defaultTemplate', this.defaultTemplate)
      } else {
        Dialog.confirm({
          title: '',
          message: '当前员工未设置工资条模板，请先设置工资条模板',
          confirmButtonColor: '#1989FA'
        })
          .then(() => {
            // on confirm
            this.$router.push({
              path: `/myCompany/addsalaryModel/companyID=${this.CompanyID}`,
              query: {jobid: this.JobId, jobuserid: this.JobUserId}
            })
          })
          .catch(() => {
            // on cancel
            // this.$router.go(-1)
          })
      }
    },

    // 获取默认模板
    initSalaryCategoryList() {
      if (!this.defaultTemplate) {
        const defaultList = [
          {
            value: '实发工资',
            insert: ''
          }
        ]
        this.list = defaultList
        return
      }

      let list = []
      for (let k in this.defaultTemplate.data[0]) {
        //遍历对象，k即为key，obj[k]为当前k对应的值
        let categoryList = this.defaultTemplate.data[0]
        if (k != 'id' && categoryList[k]) {
          let item = {
            value: categoryList[k],
            insert: ''
          }
          list.push(item)
        }
      }

      this.list = list
    },

    // 获取人员最后一次未发的工资
    async getLastNotCheckSalaryInfo() {
      let param = {
        JobUserid: this.JobUserId,
        jobId: this.JobId
      }

      const result = await this.$api.myCompany.getLastNotCheckSalaryInfo(param)
      console.log('result.data.data', result.data.length)
      if (result.code == 200 && result.data.length > 0) {
        this.inputDisabled = true
        this.hasSalaryInfo = true

        let salaryList = []
        for (let category of result.data) {
          let item = {
            value: category.categoryname,
            insert: category.money
          }
          salaryList.push(item)
        }

        this.salaryList = salaryList
        this.SalaryInfoId = result.data[0].id
        this.SalaryCategoryid = result.data[0].categoryid
      } else {
        this.inputDisabled = false
      }
    },

    goBack() {
      this.$router.push({
        path: '/myCompany/recruitStaffList',
        query: {
          jobInfoId: this.JobId,
          advaceInfoType: 3
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.row-input {
  width: 100%;
}
/deep/.insertSalary {
  .defaultSalary {
    justify-content: space-between;
    .van-cell__title {
      width: calc(100% - 40px);
      display: flex;
      -webkit-box-flex: initial;
      -webkit-flex: initial;
      -ms-flex: initial;
      flex: initial;
      span {
        white-space: nowrap;

        &:first-child {
          color: #646566;
        }
        &:last-child {
          margin-left: 15px;
          font-size: 18px;
          width: 100%;
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
    .van-cell__value {
      -webkit-box-flex: initial;
      -webkit-flex: initial;
      -ms-flex: initial;
      flex: initial;
      flex-shrink: 0;
    }
  }
}

.bottom-btn {
  width: 100%;
  position: fixed;
  bottom: 0;
  display: flex;
  padding: 0 10px 10px;
  box-sizing: border-box;
  .btn-flex {
    flex: 1;
  }
  .btn-flex + .btn-flex {
    margin-left: 10px;
  }
}
</style>